package cn.bdqn.pn.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef ="entityManagerFactoryCommodity",
                       transactionManagerRef ="transactionManagerCommodity",
                       //设置dao层所在的位置
                       basePackages = "cn.bdqn.pn.reposity.commodity")
public class RepositoryCommodityConfig {

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    @Qualifier("commodityDataSource")
    private DataSource commodityDataSource;

    @Bean(name = "entityManagerCommodity")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return  entityManagerFactoryCommodity(builder).getObject().createEntityManager();
    }


    @Bean(name = "entityManagerFactoryCommodity")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryCommodity (EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(commodityDataSource)
                .properties(getVendorProperties(commodityDataSource))
                .packages("cn.bdqn.pn.pojo.commodity") //设置实体类所在位置
                .persistenceUnit("commodityPersistenceUnit")
                .build();
    }


    private Map<String, String> getVendorProperties(DataSource dataSource) {
        jpaProperties.setDatabase(Database.MYSQL);
        Map<String,String> map = new HashMap<>();
        map.put("hibernate.dialect","org.hibernate.dialect.MySQL5Dialect");
        map.put("hibernate.physical_naming_strategy","org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl");
        jpaProperties.setProperties(map);
        return  jpaProperties.getHibernateProperties(dataSource);
    }

    @Bean(name = "transactionManagerCommodity")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryCommodity(builder).getObject());
    }

}
